import cv2
import pytesseract
import numpy as np

# 创建Harr级联器
car_haar= cv2.CascadeClassifier('/haarcascades/haarcascade_russian_plate_number.xml')

# 读取图片并灰度化
car_img = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\car.jpg")
gary = cv2.cvtColor(car_img, cv2.COLOR_BGR2GRAY)

# 检测车辆
cars = car_haar.detectMultiScale(gary, 1.1, 5)
for (x,y,w,h) in cars:
    # 画出检测框
    cv2.rectangle(car_img,(x,y),(x+w,y+h),(0,0,255),2)

    # 截取车牌区域
    car_plate = car_img[y:y+h, x:x+w]
    # 灰度化
    car_plate_gary = cv2.cvtColor(car_plate, cv2.COLOR_BGR2GRAY)

    # 二值化
    car_plate_binary = cv2.threshold(car_plate_gary, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    # 识别车牌
    print(pytesseract.image_to_string(car_plate_gary, lang='chi_sim+eng',
                                        config=f'--psm 8 --oem 3 -c tessedit_char_whitelist=0123456789ABCDEFGHJKLMNPQRSTUVWXYZ')
    )

    cv2.imshow("car",car_plate_binary)
    cv2.waitKey(0)

